<template>
  <div class="main">
    <div class="topTitle">文书档案批量导入</div>
    <div class="form_content">
      <div class="content">
        <NForm ref="formRef" label-placement="left" :label-width="130" label-align="right">
          <NFormItem>
            1.下载导入模板
            <NButton type="primary" @click="handleDownload" :loading="exportLoading"
              style="width: 115rem;margin-left: 10rem;" ghost>
              下载
            </NButton>
          </NFormItem>
          <NFormItem>2.按照Excel格式,填充数据,不要调整列顺序</NFormItem>
          <NFormItem>3.选择要导入的文件</NFormItem>
          <NFormItem>
            <NUpload accept=".xlsx,.xls" @change="handleUploadChange" style="width: 200px" :max="1"
              :default-upload="false">
              <NButton type="primary" style="width: 115rem" ghost>选择文件</NButton>
            </NUpload>
            <div style="
                display: inline-block;
                margin-left: -80rem;
                width: 200rem;
                color: rgb(104, 107, 109);
              " v-if="!fileListLengthRef">
              未选择任何文件
            </div>
          </NFormItem>
        </NForm>
      </div>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton ghost @click="goBack">
        返回
      </NButton>
      <NButton type="primary" :disabled="!fileListLengthRef" @click="confirm" ghost>
        导入
      </NButton>
    </NSpace>
  </FixedAction>


  <NModal :auto-focus="false" v-model:show="modalVisiable">
    <VDialogContentImport @close="close" @submit="submit" title="导入提示" :export="exportVisiable">
      <div style="font-size: 16rem; text-align: center; width: 400rem;word-break: break-word; ">
        <NEllipsis :line-clamp="2">
          {{ FailtrueText }}
          <template #tooltip>
            <div style="max-width: 1000px;">
              {{ FailtrueText }}
            </div>
          </template>
        </NEllipsis>
      </div>
    </VDialogContentImport>
  </NModal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import {
  NSpace,
  NButton,
  useMessage,
  NUpload,
  NForm,
  NFormItem,
  NModal,
  NEllipsis,
  type UploadFileInfo
} from 'naive-ui'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import router from '@/router'
import { sendRequest } from '@/utils/api'
import VDialogContentImport from '@/views/OA/Common/DialogContentImport.vue'

const tags = useTagStore().tags
const message = useMessage()

//下载
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const exportLoading = ref(false)
async function handleDownload() {
  exportLoading.value = true
  const [error, res, headers] = await sendRequest({
    module: 'file',
    api: 'maintenanceDownload',
    override: {
      params: {
        type: '1'
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, res)
  exportLoading.value = false
}

//导入
const importLoading = ref(false)
const fileListLengthRef: any = ref()
const fileDetail: any = ref()
async function handleUploadChange(data: { fileList: UploadFileInfo[]; file: any }) {
  fileListLengthRef.value = data.fileList.length
  fileDetail.value = data
}

const FailtrueText: any = ref()
const exportVisiable = ref(false)
const modalVisiable: any = ref(false)
async function handleClick(data: any) {
  importLoading.value = true
  const fileData = new FormData()
  fileData.append('file', data.file.file as File)
  const [error, res] = await sendRequest({
    module: 'file',
    api: 'maintenanceUpload',
    override: {
      data: {
        file: data.file.file,
        type: '1'
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code != 200) {
    FailtrueText.value = res.data
    const tmp: any = res.data?.split('导入失败').length - 1
    if (tmp > 1) {
      exportVisiable.value = true
    } else {
      exportVisiable.value = false
    }
    message.error(res.msg)
    modalVisiable.value = true
    importLoading.value = false
  } else {
    message.success(res.msg)
  }
}

//导出导入错误信息
function downloadA(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
async function handleDownloadError(data: any) {
  exportLoading.value = true
  const [error, res, headers] = await sendRequest({
    module: 'file',
    api: 'maintenanceUploadError',
    override: {
      data: {
        file: data.file.file,
        type: 1,
      }
    }
  })
  if (error) return message.error(error.message)
  downloadA(headers, res, '工资单错误数据')
  exportLoading.value = false
}

//close
const close = () => {
  modalVisiable.value = false
}

//submit
const submit = async () => {
  await handleDownloadError(fileDetail.value)
  modalVisiable.value = false
  await goBack()
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 确定
const confirm = async () => {
  await handleClick(fileDetail.value)
}
</script>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 33rem 0 180rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        width: 360rem;
        height: 130rem;
        background: #e1e1e1;
        margin-bottom: 25rem;
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

.scope {
  width: 360rem;
  height: 130rem;
  background: #e1e1e1;
  margin-bottom: 25rem;
}

.commonWidth {
  width: 360rem;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
